package com.CST.service.impl.zx;

import com.CST.entity.zx.ZxEtlAccountInfo;
import com.CST.mapper.cst.zx.ZX_FinancialMapper;
import com.CST.mapper.cst.zx.ZxBasicOpeningAmountMapper;
import com.CST.mapper.cst.zx.ZxEtlAccountInfoMapper;
import com.CST.mapper.cst.zx.ZxSumMoneyMapper;
import com.CST.mapper.ufdata.AccvouchMapper;
import com.CST.service.zx.IZxEtlAccountInfoService;
import com.CST.service.zx.IZxExpenseTypeService;
import com.CST.service.zx.IZxFinancialService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.CST.common.method.CommonMethod.getFirstDay;
import static com.CST.common.method.CommonMethod.getLastDay;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ly
 * @since 2023-03-03
 */
@Service
public class ZxEtlAccountInfoServiceImpl extends ServiceImpl<ZxEtlAccountInfoMapper, ZxEtlAccountInfo> implements IZxEtlAccountInfoService {

    @Autowired
    IZxFinancialService zxFinancialService;

    @Autowired
    IZxExpenseTypeService zxExpenseTypeService;

    @Autowired
    AccvouchMapper accvouchMapper;

    @Autowired
    ZxBasicOpeningAmountMapper basicOpeningAmountMapper;

    @Autowired
    ZxSumMoneyMapper zxSumMoneyMapper;

    @Autowired
    ZX_FinancialMapper zxFinancialMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String CollectVoucherData(int year, int month) {
        LocalDate startDate = getFirstDay(year, month);//选择月的第一天
        LocalDate endDate = getLastDay(year, month);
        LocalDate lastMonthDate = startDate.minusDays(1);
        endDate = endDate.plusDays(1);//选择月下个月的第一天
        List<String> listSplit = Arrays.asList(startDate.toString().split("-"));
        List<String> lastMonthDateSplit = Arrays.asList(lastMonthDate.toString().split("-"));
        String period = listSplit.get(0) + listSplit.get(1);
        String lastMonthPeriod = lastMonthDateSplit.get(0) + lastMonthDateSplit.get(1);

        //日期从2019年1月开始采集
        if (!period.equals("201901")) {
            //获取选择年月的期初,期末记录
            List<ZxEtlAccountInfo> isExistList = zxSumMoneyMapper.getETLAccountByPeriod(Integer.parseInt(lastMonthPeriod));

            if (isExistList == null || isExistList.size() == 0) {
                return "请先采集上月数据";
            }
        }

        //从用友获取选择月的所有凭证
        List<ZxEtlAccountInfo> zxEtlAccountInfos = accvouchMapper.CollectVoucherData(year, startDate, endDate, period);

        //从ZX_ETL_ACCOUNT_INFO中获取选择用的所有凭证
//        LambdaQueryWrapper<ZxEtlAccountInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ZxEtlAccountInfo::getPeriod, Integer.parseInt(period));
//        List<ZxEtlAccountInfo> zxEtlAccountInfosFromDB = baseMapper.selectList(queryWrapper);
//        List<String> idList = new ArrayList<>();
//        if (!zxEtlAccountInfosFromDB.isEmpty()) {
//            idList = zxEtlAccountInfosFromDB.stream().map(t -> t.getId()).collect(Collectors.toList());
//        }
//
//        //增量添加
//        List<String> finalIdList = idList;
//        zxEtlAccountInfos = zxEtlAccountInfos.stream().filter(t -> !finalIdList.contains(t.getId())).collect(Collectors.toList());

        //先删后插
        int i1 = baseMapper.delByPeriodInt(Integer.valueOf(period));

        /**药物临床试验收入转支出特殊处理
         * 凭证号accountCode为 660910 (2024年之前是这个凭证号,2024年改成 61010203 ) 且 摘要description包含"分配字样" 且货方mc<0 的凭证修改凭证
         *accountCode ='999999'
         *accountName ='药物临床试验收入转支出'
         * md = mc * (-1)
         * mc = 0
         */
        //test
//        ZxEtlAccountInfo testInfo =new ZxEtlAccountInfo();
//        BeanUtils.copyProperties(zxEtlAccountInfos.get(0),testInfo);
//        testInfo.setId("test_01");
//        testInfo.setAccountCode("660910");
//        testInfo.setDescription("测试分配");
//        testInfo.setMc(-10.00);
//        zxEtlAccountInfos.add(testInfo);


        List<ZxEtlAccountInfo> specialList =zxEtlAccountInfos.stream()
//                .filter(t->t.getAccountCode().equals("660910")//2024年之前用
                        .filter(t->t.getAccountCode().equals("61010203")//2024年开始用
                        && t.getDescription().contains("分配")
                        && t.getMc() <0
                ).collect(Collectors.toList());

        if(CollectionUtils.isNotEmpty(specialList))
        {
            specialList.forEach(item->{
                item.setAccountCode("999999");
                item.setAccountName("药物临床试验收入转支出");
                item.setMd(item.getMc()*(-1));
                item.setMc(0.00);
            });
        }


        int total = zxEtlAccountInfos.size();//为防止插入字符超过最大数,分批插入
        if (total > 0) {
            int fromIndex = 0;
            List<ZxEtlAccountInfo> insertList = new ArrayList<>();
            for (int i = 0; i < zxEtlAccountInfos.size(); i++) {
                ZxEtlAccountInfo item = zxEtlAccountInfos.get(i);
                fromIndex++;
                insertList.add(item);
                if (fromIndex % 20 == 0 && fromIndex <= total) {
                    baseMapper.insertBatch(insertList);
                    insertList = new ArrayList<>();
                }
            }
            if (CollectionUtils.isNotEmpty(insertList)) {
                baseMapper.insertBatch(insertList);
            }
//            excuteZxSumMoneyRecords(period, endPeriod, startDate, endDate);
        }


        return "success";
    }


}
